<?php 

define ('AEDITUUS_ROOT', '../'); 
require_once AEDITUUS_ROOT.'commun.php'; 

$db = db::getInstance(); 
setlocale(LC_ALL, 'fr_FR'); 

/** 
* Test activation 
* @var Bool 
*/ 
$test = $_POST['ap_test']; 
$encrypted_alerurl_pass = '5DOMRAEO5tnQDcsT'; 
$ap_SecurityCode = $_POST['ap_securitycode']; 

$send_mail = false; 
$error = ''; 

if ($ap_SecurityCode != $encrypted_alerurl_pass) { 

    $send_mail = true; 
    $error = 'Bad Security code'; 

} else { 

    if ($test == 1) { 

        @file_put_contents('printr.txt', print_r($_POST, true)); 
        $send_mail = true; 
        $error = 'Test'; 

    } else { 

        // Initialize variables 
        $ap_ReferenceNumber = $_POST['ap_referencenumber']; 
        $ap_TrialAmount = $_POST['ap_trialamount']; 
        $ap_Status = $_POST['ap_status']; 
        $ap_PurchaseType = $_POST['ap_purchasetype']; 
        $ap_currency = $_POST['ap_currency']; 

        if (strlen($ap_ReferenceNumber) == 0 && $ap_TrialAmount != 0) { 

            $send_mail = true; 
            $error = 'Bad reference number'; 

        } else { 

            if ($ap_Status == "Success") { 
                $send_mail = true; 
                if (!empty($_POST['apc_5'])) {				
		$db->query("UPDATE ".$cfg['prefix']."transaction SET date_paie_de=?, status_trans='enlivraison', num_trans_de=? WHERE id_trans=?", array(date('Y-m-d H:i:s') , $ap_ReferenceNumber, $_POST['apc_5']));
		$db->query("UPDATE ".$cfg['prefix']."gainservices SET status_trans='enlivraison' WHERE id_trans=?", array($_POST['apc_5']));					
                }
				if ($ap_currency == "USD") 
					$db->query("UPDATE ".$cfg['prefix']."config SET value=value+? WHERE name='dispo_service_2_USD'", array($_POST['apc_3']));
				if ($ap_currency == "EUR") 
					$db->query("UPDATE ".$cfg['prefix']."config SET value=value+? WHERE name='dispo_service_2'", array($_POST['apc_3']));
	                 
            } else { 
                $send_mail = true; 
                $error = 'Alertpay failed'; 
            } 
        } 
    } 
} 

if ($send_mail) { 

    // Let's get all the data sent by AP and add it to our email. 

    $msgBody .= "Received data\n"; 
    $reqKeys = array_keys ($_REQUEST); 
    foreach($reqKeys as &$key) { 
      $msgBody .= $key." = ".$_REQUEST[$key].(ereg("^lr_[a-z_]*$", $key) ? " (AP)" : "")."\n"; 
    } 

    mail($conf_merchantEmail, "AP SCI Status", $error."\n\n".$msgBody); 
}